package com.example.demo.demos.test;

import com.example.demo.demos.web.AgvLiftStorageLocationDto;
import com.example.demo.demos.web.ResponseVo;
import com.example.demo.demos.web.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
@Slf4j
public class ADD8Util {


    /**
     * 求校验和的算法 (ADD8)
     *
     * @param b 需要求校验和的字节数组
     * @return 校验和
     */
    private static byte sumCheck(byte[] b, int len){
        int sum = 0;
        for(int i = 0; i < len; i++){
            sum = sum + b[i];
        }
        if(sum > 0xff){ //超过了255，使用补码（补码 = 原码取反 + 1）
            sum = ~sum;
            sum = sum + 1;
        }
        return (byte) (sum & 0xff);
    }

    /**
     * byte转十六进制字符
     *
     * @param b byte
     * @return 十六进制字符
     */
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() == 1) {
            hex = '0' + hex;
        }
        return hex.toUpperCase(Locale.getDefault());
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int status = 3;
        if (status != 2 & status !=3){
            System.out.println("1111");
        }else {
            System.out.println("22222");
        }


        IntStream intStream = IntStream.rangeClosed(1, 5);
        Integer a5 = 0;
        Integer a6 = 0;
        Integer adf = ++a5;
        System.out.println(adf);
        Integer adf1 = a6++;
        System.out.println(adf1);
        if ((a5 != null && a5 ==0) || (a6 != null && a6 ==0)){
            System.out.println("更新数据库");
        }


        System.out.println("=============================");
        ArrayList<String> list5 = new ArrayList<>();
        ArrayList<String> list6 = new ArrayList<>();
        list5.add("111");
        int aaac = 1;
        if ((list5.isEmpty() && list6.isEmpty()) && aaac==1){
            System.out.println("关门1111");
        }

        System.out.println("==============================");
        CallPoint callPoint4 = new CallPoint();

        ArrayList<String> integers2 = new ArrayList<>();
        integers2.add("lift001");
        integers2.add("lift002");
        integers2.add("lift006");
        integers2.add("lift007");
        for (String s : integers2) {
            if (integers2.isEmpty()||s.equals("lift006")){
                break;
            }
            System.out.println(s);
        }
        System.out.println("==============================");
        int saf =2;
        if (saf < 3){
            System.out.println(789521);
        }
        boolean aaad = true;
        if (!aaad){
            System.out.println(1221);
        }
        System.out.println("=============================");
        HashMap<String, Integer> stringIntegerHashMap1 = new HashMap<>();
//        stringIntegerHashMap1.put("1",0);
        Integer integer4 = stringIntegerHashMap1.get("1");
        if (integer4 == null ){
            System.out.println("null158");
        }
        ArrayList<String> list4 = new ArrayList<>();
        list4.add("障时");
        list4.add("爱国");
        list4.add("过分");
        list4.add("撒法");
        System.out.println("-------------------------------");
        list4.forEach(a ->{ if (a.equals("爱国")) return;
            System.out.println("aa_"+a);
        });
        boolean sfe = list4.contains("过分ss");
        String s1 = list4.get(0);
        if (!s1.isEmpty()){
            String s = list4.get(list4.size() - 1);
            System.out.println("dsfsdf:"+s);
        }


        System.out.println(sfe);
        if (!sfe){
            System.out.println(1244);
        }

        List<String> names = Arrays.asList("Alice", "Bob", null, "David", null, "Eva");
        List<String> validNames = names.stream()
                .filter(Objects::nonNull)
                .map(name -> name.toUpperCase())
                .filter(name -> name.startsWith("D"))
                .collect(Collectors.toList());
        System.out.println(validNames);

        ArrayList<CallPoints> callPoints = new ArrayList<>();
        // 添加 CallPoint 对象到 list3
        CallPoints points = new CallPoints();
        points.setPointId("5-1-3");
        points.setLiftCode("lift004");
        points.setDoor(1);
        points.setState("1");
        callPoints.add(points);

        CallPoints points1 = new CallPoints();
        points1.setPointId("5-1-3");
        points1.setLiftCode("lift004");
        points1.setDoor(1);
        points1.setState("1");
        callPoints.add(points1);
        CallPoints points2 = new CallPoints();
        points2.setPointId("5-1-4");
        points2.setLiftCode("lift005");
        points2.setDoor(1);
        points2.setState("1");
        callPoints.add(points2);
        Set<String> collect5 = callPoints.stream().filter(a -> a.getState().equals("1")).map(CallPoints::getLiftCode).collect(Collectors.toSet());
        System.out.println("5555"+ collect5);
//        long count = callPoints.stream().filter(a -> a.getDoor() == 1).count();
//        System.out.println("dfasgas"+count);
        System.out.println("====================================");
        for (CallPoints callPoint : callPoints) {
            if (callPoint.getPointId().contains("5-1-4")) {
                callPoint.setLiftCode("lift00000");
            }
            System.out.println(callPoint + "ppppp");
        }
        System.out.println("====================================");
        List<String> collect3 = callPoints.stream()
                .filter(s -> s.getDoor().equals(2))
                .map(CallPoints::getLiftCode)
                .distinct()
                .collect(Collectors.toList());
        System.out.println(collect3);
        collect3.stream().forEach(s ->{
            System.out.println(s);
        });

        System.out.println("====================================");

        ArrayList<CallPoint> list3 = new ArrayList<>();
        // 添加 CallPoint 对象到 list3
        CallPoint callPoint1 = new CallPoint();
        callPoint1.setPointId("5-1-3");
        callPoint1.setLiftCode("lift004");
        callPoint1.setDoor("0");
        list3.add(callPoint1);

        CallPoint callPoint2 = new CallPoint();
        callPoint2.setPointId("5-1-3");
        callPoint2.setLiftCode("lift05");
        callPoint2.setDoor("0");
        list3.add(callPoint2);
        CallPoint callPoint3 = new CallPoint();
        callPoint3.setPointId("5-1-4");
        callPoint3.setLiftCode("lift006");
        callPoint3.setDoor("1");
        list3.add(callPoint3);
        List<CallPoint> lift0051 = list3.stream().filter(s -> s.getLiftCode().equals("lift005")).collect(Collectors.toList());
        System.out.println("打印:"+lift0051);
        list3.stream().forEach(s ->{
            String liftCode = s.getLiftCode();
            if (liftCode.equals("lift006")){
                System.out.println(liftCode);
            }
        });
        List<String> collect4 = list3.stream().map(CallPoint::getPointId).distinct().collect(Collectors.toList());
        System.out.println("4"+collect4);
        Integer integer3 = list3.stream().map(CallPoint::getDoor).map(Integer::parseInt).reduce((a, b) -> a + b).orElse(null);
        System.out.println(integer3);
//        CallPoint callPoint3 = new CallPoint();
//        callPoint3.setPointId("5-1-3");
//        callPoint3.setLiftCode("lift007");
//        callPoint3.setDoor("1");
//        list3.add(callPoint3);
        System.out.println(list3);
        // lift005 列表
        List<String> lift005 = new ArrayList<>();
        lift005.add("lift005");
//        lift005.add("lift007"); // 假设 lift007 也需要删除

        // 删除 list3 中 liftCode 在 lift005 列表中的 CallPoint 对象
        Iterator<CallPoint> iterator = list3.iterator();
        while (iterator.hasNext()) {
            CallPoint cp = iterator.next();
            if (lift005.contains(cp.getLiftCode())) {
                iterator.remove();
            }
        }

        // 打印删除后的结果
        for (CallPoint cp : list3) {
            System.out.println("PointId: " + cp.getPointId() + ", LiftCode: " + cp.getLiftCode() + ", Door: " + cp.getDoor());
        }
        System.out.println("最终结果"+list3);
        List<CallPoint> collect2 = list3.stream().collect(Collectors.toList());
        System.out.println("再转流"+collect2);


        Map<String, String> map1 = new HashMap<>();
        map1.put("a","2");
        map1.put("f","4");
        map1.put("d","6");
        Set<String> set = map1.keySet();
        System.out.println(set);


        String str = null;
        String subStr = "工单未绑定";

        boolean containsSubStr = str.contains(subStr);
        if (containsSubStr) {
            System.out.println("字符串中包含子字符串: " + subStr);
        } else {
            System.out.println("不包含子字符串: " + subStr);
        }


        ArrayList<Integer> integers1 = new ArrayList<>();
        integers1.add(125);
        integers1.add(127);
        long collect1 = integers1.stream().count();
        System.out.println(collect1);
        List<Integer> collect = integers1.stream().limit(2).collect(Collectors.toList());
        for (Integer integer : collect) {
            System.out.println(integer);
        }


        System.out.println(11);
        String hexString = "00070003a500afbbCC030600000000000029E0aa070003a500afbb";

        // 将十六进制字符串解码为字节数组
        byte[] bytes = ByteBufUtil.decodeHexDump(hexString);
        ByteBuf in = Unpooled.wrappedBuffer(bytes); // 这是您的输入ByteBuf
        byte b5 = in.readByte();
        System.out.println("打印"+b5);
        // 检查报头是否为 'aa'
        if (in.readableBytes() > 0 &&  b5== (byte) 0xcc) {
            System.out.println("cc");
//            System.out.println("in.readableBytes()" + in.readableBytes());
//            // 保存报头 'aa' 的索引位置
//            int startIdx = in.readerIndex() - 1;
//            System.out.println("保存报头 'aa' 的索引位置"+startIdx);
//
//            // 定位报尾 'bb' 的位置
//            int bbIndex = in.indexOf(in.readerIndex(), in.readableBytes()+1, (byte) 0xbb);
//            System.out.println("定位报尾 'bb' 的位置"+bbIndex);
//            int b = in.readByte();
//            System.out.println("数据长度："+b);
//            if (b ==bbIndex){
//                if (bbIndex != -1) {
//                    // 计算报文的实际长度（从报头到报尾）
//                    int lengthToRead = bbIndex - startIdx + 1;
//
//                    // 截取从报头到报尾的报文
//                    ByteBuf frame = in.slice(startIdx, lengthToRead);
//
//                    // 转换截取的报文为十六进制字符串
//                    String frameHex = ByteBufUtil.hexDump(frame);
//
//                    // 打印截取的报文
//                    System.out.println("截取的报文: " + frameHex);
//
//                    // 使用完ByteBuf后，记得释放它以避免内存泄漏
//                    frame.release();
//                } else {
//                    System.out.println("未找到报尾 'bb'");
//                }
//            }
        } else if (b5 == (byte) 0x00){
            System.out.println("报头00");
        }else {
            System.out.println(1118);
        }







        String aui = "3";
        if ((aui == "1") || (aui == "2")) {
            // 如果aui是"1"或"2"，这里不执行任何操作
        } else {
            System.out.println("错误"); // 如果aui不是"1"或"2"，打印错误
        }



        Integer aaag = 0;
        Integer aaags= 5;
        if (!aaags.equals(aaag)){
            System.out.println("不相同");
        }


        Integer sa = 1;
        boolean f = false;
        if (sa == 1 && f){
            System.out.println("执行修改数据库");
            f = true;
            System.out.println(f);
        }



        String aaa = "1";
        String bb = "3";
        if (aaa.equals("2") | bb.equals("2")){
            System.out.println("46115565");
        }
        byte a4 = 2;
        if (a4 == (byte) 0x02){
            System.out.println("byteDENGYU");
        }else if (a4 != (byte) 0x02){
            System.out.println("!!!!!!");
        }


        ArrayList<ResponseVo> agvTaskList1 = new ArrayList<>();
        ResponseVo responseVo = new ResponseVo();
        responseVo.setReturnCode(1);
        responseVo.setReturnReason("102");
        agvTaskList1.add(responseVo);
        ResponseVo agvTaskFor1Location = agvTaskList1.stream()
                .filter(a -> a.getReturnReason().endsWith("01"))
                .findAny()
                .orElse(null);
        if (agvTaskFor1Location == null){
            System.out.println("01储位为空");
        }
        System.out.println("不为空，打印输出："+ agvTaskFor1Location);


        HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
        stringIntegerHashMap.put("1",00);
        Integer integer2 = stringIntegerHashMap.get("1");
        System.out.println(integer2);
        if (integer2 ==0){
            System.out.println("成功为0");
        }

        System.out.println(LocalDateTime.now());

        Map<String, Integer> map = new HashMap<>();
        map.put("1",1);
        System.out.println("1111"+map.values());
        Integer integer1 = map.get("1");
        if (integer1 == null){
            System.out.println("回滚");
        }else {
            map.remove("1");
            System.out.println("不为空");
            System.out.println(integer1);
        }
        System.out.println("222"+map.values());

        ArrayList<String> list2 = new ArrayList<>();
        list2.add("301");
        list2.add("302");
        for (int i = 0; i < list2.size(); i++) {
            System.out.println("下标值：{}"+ i);
        }


        ArrayList<String> storagePointList  = new ArrayList<>();
        Map<String, Integer> endsWithCount = new HashMap<>();
        storagePointList.add("102");
        storagePointList.add("102");
        storagePointList.stream()
                .map(s -> s.endsWith("1") ? "1" : s.endsWith("2") ? "2" : "other")
                .forEach(s -> endsWithCount.put(s, endsWithCount.getOrDefault(s, 0) + 1));

// 检查是否正好有一个以"1"结尾，一个以"2"结尾
        boolean b3 = endsWithCount.getOrDefault("1", 0) == 1;
        boolean b4 = endsWithCount.getOrDefault("2", 0) == 1;

        if (!b3 || !b4) {
            System.out.println("电梯储位已配置，不能重复配置电梯储位");
        }else {
            System.out.println("配置成功");
        }

        byte aa = -94;
        if (aa !=(byte) 0xA2){
            System.out.println("不等于");
        }else {
            System.out.println("等于");
        }

        String liftCode = "lift006";
        List<String>storagePointList1  = new ArrayList<>();
        storagePointList1.add("601");
        storagePointList1.add("603");
        storagePointList1.add("605");
        if (storagePointList1.size() !=2){
            System.out.println("电梯储位未配全");
        }

        char c = liftCode.charAt(liftCode.length() - 1);
        String value = String.valueOf(c);
        System.out.println(c);
        boolean b = storagePointList1.stream().allMatch(s -> s.startsWith(value));
        System.out.println("是否包含6："+b);
        if (!b){
            System.out.println("储位输入错误");
        }

        boolean b1 = storagePointList1.get(0).endsWith("1");
        boolean b2 = storagePointList1.get(1).endsWith("2");
        System.out.println("是否为1结尾:"+b1);
        if (!b1 || !b2){
            System.out.println("电梯储位配置错误");
        }

        ArrayList<String> list1 = new ArrayList<>();
        list1.add("1");
        list1.add("2");
        ArrayList<User> users = new ArrayList<>();
        for (String s : list1) {
            User user = new User();
            user.setName(s);
            user.setAge(6);
            users.add(user);
        }
        for (User user1 : users) {
            System.out.println(user1.toString());

        }
//        list1.add("3");
//        list1.add("4");
//        String s1 = list1.get(0);
//        list1.clear();
        System.out.println("清空数据："+list1);


        String a = "Firefighting";
        if (a.equals("Firefighting")){
            System.out.println("Firefighting");
        }



        ArrayList<String> list = new ArrayList<>();
        list.add("111");
        list.add("222");
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(101);
        integers.add(102);
        int sss = 0;
        for (String s : list) {
            Integer integer = integers.get(sss);
            System.out.println(s+"打印:" +integer);
            sss++;
        }

        String ss = "";
        if (ss.isEmpty()){
            System.out.println("11111111111");
        }else {
            System.out.println("有数据"+ss);
        }

//        if (1 !=1){
//            System.out.println("fa;se");
//        }
//
//
//        boolean a = true;
//        if (!a){
//            System.out.println("false");
//        }else if (a){
//            System.out.println("true");
//        }
//        String a1 = "Inbound";
//        if (a1.equals( LiftType.Inbound)) {
//            System.out.println(111);
//        }else {
//            System.out.println(222);
//        }


//        final AtomicCounter counter = new AtomicCounter();
//        for (int i = 0; i < 10; i++) {
//            counter.increment();
//            int count = counter.getCount();
//            System.out.println("当前值"+count);
//        }
    }



//        AgvLiftStorageLocationDto dto = new AgvLiftStorageLocationDto();
//        dto.setAgvId("agv001");
//        dto.setLiftCode("lift004");
//        dto.setStoragePoint("5555");
//        String WCS_URL = "http://".concat("localhost").concat(":").concat("8081").concat("/lift/enter");
//        try {
//            ObjectMapper objectMapper = new ObjectMapper();
//            // 将wcsRequest转为json格式
//            String jsonBody = objectMapper.writeValueAsString(dto);
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_JSON);
//            HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);
//            // 将响应体转为wcsResponse
//            RestTemplate restTemplate = new RestTemplate();
//            ResponseEntity<String> responseEntity = restTemplate.postForEntity(WCS_URL, requestEntity, String.class);
//            String responseBody = responseEntity.getBody();
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }


//        HashMap<String, String> hashMap = new HashMap<>();
//        hashMap.put("查询电梯工作状态" + "lift004","lift004");
//        System.out.println("打印map："+ hashMap.keySet());
//        String aaa = hashMap.get("查询电梯工作状态" + "lift004");
//        if (aaa == null){
//            System.out.println("null");
//        }
//        if (aaa != null){
//            System.out.println("不等于null");
//        }
//        System.out.println("------------------------------------------");
//
//
//            // 01 01 01 FF FF FF FF FF FF
//            byte[] b = new byte[9];
//            b[0] = (byte) 0x09;
//            b[1] = (byte) 0x00;
//            b[2] = (byte) 0x00;
//            b[3] = (byte) 33;
//            b[4] = (byte) 1;
//            b[5] = (byte) 3;
//            b[6] = (byte) 0x01;
////            b[8] = (byte) 0x00;
////            b[7] = (byte) 0x00;
//            byte result = sumCheck(b, 8);
//        String s = byteToHex(result);//正确的结果应该是FD
//        System.out.println(s);
//        byte b3 = Byte.parseByte(s, 16);
//        System.out.println("string类型转byte类型结果:"+b3);
//        ByteBuf buffer = Unpooled.buffer(10);
//        buffer.writeByte(0x49);
//        buffer.writeByte(result);
//        byte b1 = buffer.readByte();
//        byte b2 = buffer.readByte();
//        System.out.println("添加0x49,打印结果:{},"+ b1 +"49打印出来的结果:{}" + b2);
    }